package top.malaoshi.webmvc.factory;

import top.malaoshi.webmvc.exception.BeanCreationException;
import top.malaoshi.webmvc.info.ClassInfo;

import java.lang.reflect.Constructor;

public class DefaultObjectFactory implements ObjectFactory{

    private ClassInfo classInfo;

    public DefaultObjectFactory(ClassInfo classInfo) {
        this.classInfo = classInfo;
    }

    @Override
    public Object getObject() throws BeanCreationException {
        // 不能使用 clazz.newInstance() 创建对象，遇到 private 私有构造方法会报错无权限
        try {
            Class clazz = classInfo.getClazz();
            Constructor<?> constructor = clazz.getDeclaredConstructor();
            // 设置访问权限，无视private关键字
            constructor.setAccessible(true);
            Object bean = constructor.newInstance();
            return bean;
        } catch (Exception e) {
            throw new BeanCreationException(e);
        }
    }
}
